package com.googlecode.geoteacher.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.DigestInputStream;
import java.security.MessageDigest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public final class JsonUtils {

	private static final String DEFAULT_CHARSET = "utf-8";
	private static final String NEW_LINE = "\n";

	private JsonUtils() {
	}

	private static String load(InputStream in, MessageDigest digest)
			throws IOException {

		if (in == null) {
			throw new NullPointerException("input stream is null");
		}

		if (digest != null) {
			in = new DigestInputStream(in, digest);
		}

		BufferedReader br = new BufferedReader(new InputStreamReader(in,
				DEFAULT_CHARSET));

		StringBuilder str = new StringBuilder();
		String line;

		while ((line = br.readLine()) != null) {
			str.append(line).append(NEW_LINE);
		}

		return str.toString();
	}

	private static String load(URL url, MessageDigest digest)
			throws IOException {
		
		InputStream in = url.openStream();
		String string = load(in, digest);
		in.close();
		return string;
	}

	public static JSONObject loadObject(InputStream in, MessageDigest digest)
			throws JSONException, IOException {
		return new JSONObject(load(in, digest));
	}

	public static JSONObject loadObject(InputStream in) throws JSONException,
			IOException {
		return new JSONObject(load(in, null));
	}

	public static JSONObject loadObject(URL url, MessageDigest digest)
			throws JSONException, IOException {
		return new JSONObject(load(url, digest));
	}

	public static JSONObject loadObject(URL url) throws JSONException,
			IOException {
		return new JSONObject(load(url, null));
	}

	public static JSONArray loadArray(InputStream in, MessageDigest digest)
			throws JSONException, IOException {
		return new JSONArray(load(in, digest));
	}

	public static JSONArray loadArray(InputStream in) throws JSONException,
			IOException {
		return new JSONArray(load(in, null));
	}

	public static JSONArray loadArray(URL url, MessageDigest digest)
			throws JSONException, IOException {
		return new JSONArray(load(url, digest));
	}

	public static JSONArray loadArray(URL url) throws JSONException,
			IOException {
		return new JSONArray(load(url, null));
	}
}